package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //获取所有分类信息并以父子关系展示封装返回给前端
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> levelOne = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map(menu -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                }
        ).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        return levelOne;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {

        //TODO 检查当前删除的菜单，是否被其他地方引用
        //查询哪里引用了分类菜单看是否存在引用
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("调用了此用法");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    /**
     * 优化一 一次查询数据库得到结果，然后从结果中获取数据
     * 优化二 使用缓存redis存储查询出来的数据
     *
     * @return
     */
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        String catagoryJson = redisTemplate.opsForValue().get("catagoryJson");
        if (StringUtils.isEmpty(catagoryJson)) {
            System.out.println("缓存不命中。。。查询数据库");
            //获取数据并存入redis
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();

            return catalogJsonFromDb;
        }
        System.out.println("缓存命中。。。没有查询数据库");
        Map<String, List<Catalog2Vo>> stringListMap = JSON.parseObject(catagoryJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return stringListMap;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dataFromDb = null;
        try {
            dataFromDb = getDataFromDb();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return dataFromDb;
    }

    //加锁解锁保持原子性
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);//抢占分布式锁
        if (lock) {
            System.out.println("获取分布式锁成功");
            Map<String, List<Catalog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        } else {
            System.out.println("获取分布式锁失败");
            try {
                Thread.sleep(200);
            } catch (Exception e) {

            }
            return getCatalogJsonFromDbWithRedisLock();//自旋的方式
        }

    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        String catagoryJson = redisTemplate.opsForValue().get("catagoryJson");
        if (!StringUtils.isEmpty(catagoryJson)) {
            Map<String, List<Catalog2Vo>> stringListMap = JSON.parseObject(catagoryJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return stringListMap;
        }
        System.out.println("查询了数据库。。。");

        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //拿到所有的一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //封装map
        Map<String, List<Catalog2Vo>> listMap = level1Categorys.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), l2 -> {
            //所有2级分类
            List<CategoryEntity> category2Entities = getParent_cid(selectList, l2.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (category2Entities != null) {
                catalog2Vos = category2Entities.stream().map(item -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(l2.getCatId().toString(), item.getCatId().toString(), item.getName(), null);
                    List<CategoryEntity> category3Entities = getParent_cid(selectList, item.getCatId());
                    if (category3Entities != null) {
                        List<Catalog2Vo.Catalog3Vo> catalog3VoList = category3Entities.stream().map(item3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(item.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3VoList);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        String s = JSON.toJSONString(listMap);
        redisTemplate.opsForValue().set("catagoryJson", s, 1, TimeUnit.DAYS);
        return listMap;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithLocalLock() {
//        synchronized (this) {
//            return getDataFromDb();
//        }
        return getDataFromDb();
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid().equals(parent_cid)).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }

        return paths;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> entities) {
        List<CategoryEntity> childrenMenu = entities.stream().filter(categoryEntity ->
        {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, entities));
            return categoryEntity;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return childrenMenu;
    }

}